package com.cll.learn.rabbitmq.listener;

import com.cll.learn.rabbitmq.entity.Order;
import com.cll.learn.rabbitmq.mapper.OrderMapper;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 描述信息:
 * 下单的监听器，接收下单消息
 * @author CLL
 * @version 1.0
 * @date 2021/2/28 19:15
 */
@Component
public class RabbitMQOrderListener {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMQOrderListener.class);

    @Autowired
    OrderMapper orderMapper;

    /**
     * 接收下单消息，然后持久化到数据库，持久化成功之后，手动确认消息
     * @param order 订单信息
     * @param channel   连接信道
     * @param message   消息对象
     * @throws IOException  手动确认消息IO异常
     */
    @RabbitListener(queues = "queue.order", ackMode = "MANUAL")
    public void onMessage(Order order, Channel channel, Message message) throws IOException {
        logger.info("===>>> 接收到订单消息队列订单信息 = {}", order);
        int i = orderMapper.insertOrder(order);
        if (i == 1) {
            // 确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            logger.error("****** 持久化订单信息失败");
        }

    }
}